package com.winning.core.job.factory;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

/**
 * 任务调度公共类
 *
 * @author lws
 * @remark
 * @time 2015-4-9下午3:04:12
 */
public class QuartzJobFactory {
    private static Logger LOGGER = Logger.getLogger("pbsLoger");

    public final static String JOB_NAME_FIX = "JOB_";
    public final static String TRIGGER_NAME_FIX = "TRIGGER_";

    //任务组名
    public final static String JOB_GROUP_NAME = "QUARTZ_JOBGROUP_NAME";

    //触发器组名
    public final static String TRIGGER_GROUP_NAME = "QUARTZ_TRIGGERGROUP_NAME";

    /**
     * 添加任务的方法
     *
     * @param jobName        任务名
     * @param triggerName    触发器名
     * @param scheduler      任务调度器
     * @param jobClass       执行任务的类
     * @param cronExpression Cron表达式 "* * 11-12 * * ?"
     * @param jobListener    任务监听器
     * @throws SchedulerException
     */
    public static Scheduler createJob(String jobName, String triggerName, Scheduler scheduler,
                                      Class<? extends Job> jobClass, String cronExpression, Map<String, Object> jobDataMap, JobListener jobListener) throws SchedulerException {
        //用于描叙Job实现类及其他的一些静态信息，构建一个作业实例
        JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, jobClass);

        if (jobListener != null) {
            //addJobListener必须在scheduleJob之前执行
            scheduler.addJobListener(jobListener);

            //给任务增加局部监听器
            jobDetail.addJobListener(jobListener.getName());
        }

        //设置参数列表
        for (Entry<String, Object> entry : jobDataMap.entrySet()) {
            jobDetail.getJobDataMap().put(entry.getKey(), entry.getValue());
        }

        //构建一个触发器，规定触发的规则
        CronTrigger cronTriggerBean = new CronTrigger(triggerName, TRIGGER_GROUP_NAME);
        try {
            cronTriggerBean.setCronExpression(cronExpression);
            cronTriggerBean.setMisfireInstruction(CronTrigger.MISFIRE_INSTRUCTION_FIRE_ONCE_NOW);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //向Scheduler中添加job任务和trigger触发器
        scheduler.scheduleJob(jobDetail, cronTriggerBean);

        return scheduler;
    }

    /**
     * @param @param scheduler
     * @param @param jobName
     * @param @param jobGroupName
     * @return void
     * @throws
     * @Title: removeJob
     * @Description: 删除特定任务
     */
    public static void removeJob(Scheduler scheduler, String jobName, String jobGroupName) {
        if (scheduler != null) {
            try {
                scheduler.deleteJob(jobName, jobGroupName);
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    }

}
